/*
import axios from "axios";

/!**
 * 创建api公共访问路径
 * @type {axios.AxiosInstance}
 *!/
const httpInstance=axios.create({
    baseURL: "http://192.168.1.245:8083",
     //baseURL: `${import.meta.env.VITE_APP_API_BASE_URL}/api`,
    // baseURL: `${import.meta.env.VITE_APP_API_BASE_URL}/api`,
    timeout: 200000,
})

/!**
 *
 * axios 响应拦截器
 *!/
httpInstance.interceptors.response.use(
    response => response.data,
    error => {
        console.log(error)
        return Promise.reject(error);
    }

)
/!**
 * axios 请求拦截器
 *!/
httpInstance.interceptors.request.use(
    config => {
        return config;
    },e=> {
        console.log(e)
        return Promise.reject(e);
    }
)

export default httpInstance;
*/



import axios from "axios";
import { useUserStore } from "@/stores/userStore"; // 假设使用Pinia存储用户状态
import { storeToRefs } from "pinia";
/**
 * 创建API公共访问路径
 * @type {axios.AxiosInstance}
 */
const httpInstance = axios.create({
    //baseURL: "http://192.168.1.245:8083",
    baseURL: `${import.meta.env.VITE_APP_API_BASE_URL}/apis`,
    timeout: 200000,
});

/**
 * axios 请求拦截器
 * 添加JWT令牌到请求头
 */
httpInstance.interceptors.request.use(
    config => {
        const userStore = useUserStore();
        const { token } = storeToRefs(userStore); // 解构响应式令牌
        // 仅当令牌存在时添加请求头（避免空值导致的错误）
        if (token.value && token.value !== 'undefined') {
            // 对于非OPTIONS请求添加令牌
            if (config.method !== 'options' && token.value) {
                config.headers.Authorization = `Bearer ${token.value}`;
            }
            console.log("token=>", token.value);
           // config.headers.Authorization = `Bearer ${token.value}`;
        } else {
            // 可选：记录无令牌的请求，便于调试
            console.warn("请求未携带令牌:", config.url);
        }
        return config;
    },
    error => {
        console.error("请求拦截器错误:", error);
        return Promise.reject(error);
    }
);

/**
 * axios 响应拦截器
 * 处理401未授权错误，自动刷新令牌或跳转到登录页
 */
httpInstance.interceptors.response.use(
    response => response.data,
    async error => {
        console.error("响应拦截器错误:", error);
        const originalRequest = error.config;
        const status = error.response?.status;

        // 处理401未授权错误
        if (status === 401) {
            const userStore = useUserStore();

            // 如果是登录请求本身失败，直接跳转登录页
            if (originalRequest.url.includes("/oauth/token")) {
                userStore.clearToken();
                window.location.href = "/#/login";
                return Promise.reject(error);
            }

            // 尝试使用刷新令牌获取新的访问令牌
            try {
                const refreshToken = localStorage.getItem("refresh_token");
                if (!refreshToken) throw new Error("刷新令牌不存在");

                // 发送刷新令牌请求
                const refreshResponse = await axios.post(
                    `${httpInstance.defaults.baseURL}/oauth/token`,
                    new URLSearchParams({
                        grant_type: "refresh_token",
                        client_id: "ZhuangjiWebApp",
                        client_secret: "ZhuangjiWebApp",
                        refresh_token: refreshToken
                    }),
                    {
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        }
                    }
                );

                // 更新令牌
                userStore.setToken(refreshResponse.data.access_token);
                localStorage.setItem("refresh_token", refreshResponse.data.refresh_token);

                // 重试原始请求
                originalRequest.headers.Authorization = `Bearer ${refreshResponse.data.access_token}`;
                return httpInstance(originalRequest);
            } catch (refreshError) {
                // 刷新令牌失败，跳转到登录页
                console.error("刷新令牌失败:", refreshError);
                userStore.clearToken();
                window.location.href = "/#/login";
                return Promise.reject(refreshError);
            }
        }

        return Promise.reject(error);
    }
);

export default httpInstance;